package com.my.blogapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.my.blogapi.dao.pojo.SysUser;
import com.my.blogapi.service.LoginService;
import com.my.blogapi.service.SysUserService;
import com.my.blogapi.utils.JWTUtils;
import com.my.blogapi.vo.ErrorCode;
import com.my.blogapi.vo.LoginUserVo;
import com.my.blogapi.vo.param.LoginParams;
import com.my.blogapi.vo.param.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class LoginServiceImpl implements LoginService {
    //定义加密盐
    private static final String slot = "blog";
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(LoginParams loginParams) {

        /**
         * 1.检查参数是否合法
         * 2.根据用户名和密码去表中查询是否存在
         * 3.如果不存在，登录失败
         * 4.如果存在，生成token返回给前端
         * 5.token存入redis中 token：user 设置过期时间
         * （登录认证的时候，先验证token字符串是否合法，去redis中验证是否存在）
         *
         */
        String password = loginParams.getPassword();
        String account = loginParams.getAccount();
        if (StringUtils.isBlank(password) || StringUtils.isBlank(account)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        //对密码进行MD5加密
        password = DigestUtils.md5Hex(password+slot);
        SysUser sysUser = sysUserService.findSysUser(account, password);
        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        //生成token
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("Token_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * 用户注册
     * @param loginParam
     * @return
     */
    @Override
    public Result register(LoginParams loginParam) {
        //判断参数是否合法
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname = loginParam.getNickname();
        if (StringUtils.isBlank(account)
                || StringUtils.isBlank(password)
                || StringUtils.isBlank(nickname)
        ){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        //查询数据库中是否存在该用户
        SysUser sysUser = sysUserService.findSysUserByAccount(account);
        if (sysUser!=null){
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        //注意密码需要加盐
        sysUser.setPassword(DigestUtils.md5Hex(password+slot));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.save(sysUser);
        //生成成功返回token
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("Token_"+token,JSON.toJSONString(sysUser),1,TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @Override
    public Result loginOut(String token) {
        //清除redis中对应的token
        redisTemplate.delete("Token_"+token);
        return Result.success(null);
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @Override
    public Result currentUser(String token) {
        SysUser user = sysUserService.findSysUserByToken(token);
        if (user==null){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        //返回用户信息
        LoginUserVo loginUserVo = new LoginUserVo();
        BeanUtils.copyProperties(user,loginUserVo);
        return Result.success(loginUserVo);
    }

    @Override
    public SysUser checkToken(String token) {
        if (StringUtils.isBlank(token)){
            return null;
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null){
            return null;
        }
        String userJson = (String) redisTemplate.opsForValue().get("Token_" + token);
        if (StringUtils.isBlank(userJson)){
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }


}
